package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/hub"
	"FeedXmh/tdengine"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"github.com/xuri/excelize/v2"
	"paco_toolkit/DMXFGW"
	"paco_toolkit/common"
	"time"
)

var Feed_his = feed_his{}

type feed_his struct {
}

func (a *feed_his) GetPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	his_date := gconv.String(params["his_date"])

	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])
	sn := gconv.String(params["sn"])

	health := gconv.String(params["health"])
	mode := gconv.String(params["mode"])

	if begin == "" && end == "" && his_date == "" {
		res["code"] = -2
		res["msg"] = "非法参数"
	} else if farmid == "" && houseid == "" && sn == "" {
		res["code"] = -2
		res["msg"] = "非法参数"
	} else {
		where := " 1=1 "

		if begin != "" {
			where += fmt.Sprintf(" and his_date>='%s' ", begin)
		}
		if end != "" {
			where += fmt.Sprintf(" and his_date<='%s' ", end)
		}
		if his_date != "" {
			where += fmt.Sprintf(" and his_date='%s' ", his_date)
		}
		if farmid != "" {
			where += fmt.Sprintf(" and farmid=%s ", farmid)
		}
		if houseid != "" {
			where += fmt.Sprintf(" and houseid=%s ", houseid)
		}
		if sn != "" {
			where += fmt.Sprintf(" and sn='%s' ", sn)
		}
		if health != "" {
			where += fmt.Sprintf(" and health='%s' ", health)
		}
		if mode != "" {
			where += " and p.mode in (" + mode + ") "
		}

		claims := jwt.ExtractClaims(r)
		userid := claims["userid"].(string)
		url := r.URL.Path
		if dao.CheckApiPermission(url, r.Method, userid) {
			//管理员可以看到全部，其他角色按照权限获取
			if dao.IsAdmin(userid) || dao.IsService(userid) {

			} else {

			}

			db := g.DB(g.Cfg().GetString("custom.db_name"))
			sql := fmt.Sprintf(`SELECT COUNT(0) as count FROM t_hzfgw_node_status_his his
INNER JOIN t_device d ON d.device_addr = his.addr
INNER JOIN t_house h ON h.id = d.houseid
INNER JOIN t_farm f ON f.id = h.farmid
LEFT JOIN t_hzfgw_node_para p ON p.sn = his.sn and p.addr=his.addr where %s`, where)
			one, err := db.GetOne(sql)
			if err != nil {
				g.Log().Line().Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				res["count"] = one.Map()["count"]
				start := limit*page - limit
				if start < 0 {
					start = 0
				}
				if order == "" {
					order = " farmname,housename,hnum ASC"
				}
				sql = fmt.Sprintf(`SELECT f.id as farmid,f.farmname,h.id as houseid,h.housename,d.remark as unit_name,d.device_type,p.pig_num as para_pig_num,p.hnum,his.* FROM t_hzfgw_node_status_his his
INNER JOIN t_device d ON d.device_addr = his.addr
INNER JOIN t_house h ON h.id = d.houseid
INNER JOIN t_farm f ON f.id = h.farmid
LEFT JOIN t_hzfgw_node_para p ON p.sn = his.sn and p.addr=his.addr where %s ORDER BY %s limit %d,%d`, where, order, start, limit)
				records, error := db.GetAll(sql)
				if error != nil {
					g.Log().Line().Error(error)
					res["msg"] = error.Error()
					res["code"] = -1
				} else {
					list := records.List()

					for k, _ := range list {
						id := gconv.Int(list[k]["id"])
						_mode := gconv.Int(list[k]["mode"])
						_model := gconv.String(list[k]["model"])
						day := gconv.Int(list[k]["day"])
						para_pig_num := gconv.Int(list[k]["para_pig_num"])
						pig_num := gconv.Int(list[k]["pig_num"])
						if pig_num == 0 {
							//status_his的猪只数量没有，需要刷新status_his
							pig_num = para_pig_num
							//计算

							day_use_feed_auto := gconv.Float32(list[k]["day_use_feed_auto"])
							day_use_feed_man := gconv.Float32(list[k]["day_use_feed_man"])
							day_use_feed := day_use_feed_man + day_use_feed_auto
							var avg_day_use_feed float32
							if pig_num > 0 {
								avg_day_use_feed = day_use_feed / float32(pig_num)
							}

							list[k]["pig_num"] = pig_num
							//list[k]["day_use_feed"] = day_use_feed
							//list[k]["avg_day_use_feed"] = avg_day_use_feed

							var health string
							var low, standard, high float32
							low, standard, high = hub.GetStandard(_model, _mode, day)
							if low <= avg_day_use_feed && avg_day_use_feed <= high {
								//正常采食
								health = "good"
							} else {
								if low > avg_day_use_feed {
									//低采食
									health = "low"
								} else if high < avg_day_use_feed {
									//高采食
									health = "high"
								}
							}
							list[k]["low_standard"] = low
							list[k]["high_standard"] = high
							list[k]["standard"] = standard
							list[k]["health"] = health

							//update
							his, _ := dao.T_hzfgw_node_status_his.GetById(id)
							if his != nil {
								his["pig_num"] = pig_num
								his["avg_feed"] = avg_day_use_feed
								his["low_standard"] = low
								his["high_standard"] = high
								his["standard"] = standard
								his["health"] = health
								his["lasttime"] = common.NowString()
								his["source"] = 1 //记录更新
								dao.T_hzfgw_node_status_his.Save(his)
							}
						}
					}

					res["code"] = 0
					res["data"] = list
				}
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feed_his) Get(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	order := r.GetString("order")
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])
	sn := gconv.String(params["sn"])

	if begin == "" || end == "" {
		res["code"] = -2
		res["msg"] = "非法参数"
	} else if farmid == "" && houseid == "" && sn == "" {
		res["code"] = -2
		res["msg"] = "非法参数"
	} else {
		where := " 1=1 "
		where += fmt.Sprintf(" and his_date>='%s' and his_date<='%s'", begin, end)
		if farmid != "" {
			where += fmt.Sprintf(" and farmid=%s ", farmid)
		}
		if houseid != "" {
			where += fmt.Sprintf(" and houseid=%s ", houseid)
		}
		if sn != "" {
			where += fmt.Sprintf(" and sn='%s' ", sn)
		}

		claims := jwt.ExtractClaims(r)
		userid := claims["userid"].(string)
		url := r.URL.Path
		if dao.CheckApiPermission(url, r.Method, userid) {
			//管理员可以看到全部，其他角色按照权限获取
			if dao.IsAdmin(userid) || dao.IsService(userid) {

			} else {

			}

			db := g.DB(g.Cfg().GetString("custom.db_name"))
			if order == "" {
				order = " farmname,housename,hnum ASC"
			}
			sql := fmt.Sprintf(`SELECT f.id as farmid,f.farmname,h.id as houseid,h.housename,d.remark as unit_name,d.device_type,p.hnum,p.son,p.feed_alarm_diff,his.* FROM t_hzfgw_node_status_his his
INNER JOIN t_device d ON d.device_addr = his.addr
INNER JOIN t_house h ON h.id = d.houseid
INNER JOIN t_farm f ON f.id = h.farmid
LEFT JOIN t_hzfgw_node_para p ON p.sn = his.sn and p.addr=his.addr where %s ORDER BY %s `, where, order)
			records, err := db.GetAll(sql)
			if err != nil {
				g.Log().Line().Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				list := records.List()
				res["code"] = 0
				res["data"] = list
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

// Export 日采食记录
func (a *feed_his) Export(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	order := r.GetString("order")
	//his_date := gconv.String(params["date"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])
	sn := gconv.String(params["sn"])

	if begin == "" || end == "" {
		res["code"] = -2
		res["msg"] = "非法参数"
		r.Response.WriteJson(res)
	} else if farmid == "" && houseid == "" && sn == "" {
		res["code"] = -2
		res["msg"] = "非法参数"
		r.Response.WriteJson(res)
	} else {
		where := " 1=1 "
		where += fmt.Sprintf(" and his_date>='%s' and his_date<='%s'", begin, end)
		if farmid != "" {
			where += fmt.Sprintf(" and farmid=%s ", farmid)
		}
		if houseid != "" {
			where += fmt.Sprintf(" and houseid=%s ", houseid)
		}
		if sn != "" {
			where += fmt.Sprintf(" and p.sn='%s' ", sn)
		}

		claims := jwt.ExtractClaims(r)
		userid := claims["userid"].(string)
		url := r.URL.Path
		if dao.CheckApiPermission(url, r.Method, userid) {
			//管理员可以看到全部，其他角色按照权限获取
			if dao.IsAdmin(userid) || dao.IsService(userid) {

			} else {
				//where += fmt.Sprintf(" and addr in (SELECT device_addr FROM t_user_device WHERE userid='%s')",userid)
			}

			db := g.DB(g.Cfg().GetString("custom.db_name"))
			if order == "" {
				order = " farmname,housename,hnum ASC"
			}
			sql := fmt.Sprintf(`SELECT f.id as farmid,f.farmname,h.id as houseid,h.housename,d.remark as unit_name,d.device_type,p.pig_num as para_pig_num,p.hnum,his.* FROM t_hzfgw_node_status_his his
INNER JOIN t_device d ON d.device_addr = his.addr
INNER JOIN t_house h ON h.id = d.houseid
INNER JOIN t_farm f ON f.id = h.farmid
LEFT JOIN t_hzfgw_node_para p ON p.sn = his.sn and p.addr=his.addr where %s ORDER BY %s `, where, order)
			records, err := db.GetAll(sql)
			if err != nil {
				g.Log().Line(true).Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
				r.Response.WriteJson(res)
			} else {
				f := excelize.NewFile()
				defer func() {
					if err := f.Close(); err != nil {
						g.Log().Line(true).Error(err)
					}
				}()

				// 创建一个工作表
				index, err := f.NewSheet("Sheet1")
				if err != nil {
					g.Log().Line(true).Error(err)
				}

				//样式
				style_header, _ := f.NewStyle(&excelize.Style{
					Fill:      excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
					Font:      &excelize.Font{Color: "#ffffff", Bold: true},
					Alignment: &excelize.Alignment{Vertical: "center", Horizontal: "center"},
				})

				style_yellow_font, _ := f.NewStyle(&excelize.Style{
					Font: &excelize.Font{Color: "#FF8010"},
				})
				style_yellow_light_font, _ := f.NewStyle(&excelize.Style{
					Font: &excelize.Font{Color: "#FFB800"},
				})
				style_green_font, _ := f.NewStyle(&excelize.Style{
					Font: &excelize.Font{Color: "#05982E"},
				})

				//列宽
				f.SetColWidth("Sheet1", "A", "Z", 20)
				// 标题
				f.SetCellValue("Sheet1", "A1", "场区")
				f.SetCellValue("Sheet1", "B1", "单元")
				f.SetCellValue("Sheet1", "C1", "栏位")
				f.SetCellValue("Sheet1", "D1", "运行模式")
				f.SetCellValue("Sheet1", "E1", "日龄")
				f.SetCellValue("Sheet1", "F1", "采食日期")
				f.SetCellValue("Sheet1", "G1", "存栏")
				f.SetCellValue("Sheet1", "H1", "总采食(kg)")
				f.SetCellValue("Sheet1", "I1", "头均采食(kg)")
				f.SetCellValue("Sheet1", "J1", "采食状况")
				f.SetCellValue("Sheet1", "K1", "头均低区间(kg)")
				f.SetCellValue("Sheet1", "L1", "头均正常区间(kg)")
				f.SetCellValue("Sheet1", "M1", "头均高区间(kg)")
				f.SetCellValue("Sheet1", "N1", "饮水量(L)")

				f.SetCellStyle("Sheet1", "A1", "A1", style_header)
				f.SetCellStyle("Sheet1", "B1", "B1", style_header)
				f.SetCellStyle("Sheet1", "C1", "C1", style_header)
				f.SetCellStyle("Sheet1", "D1", "D1", style_header)
				f.SetCellStyle("Sheet1", "E1", "E1", style_header)
				f.SetCellStyle("Sheet1", "F1", "F1", style_header)
				f.SetCellStyle("Sheet1", "G1", "G1", style_header)
				f.SetCellStyle("Sheet1", "H1", "H1", style_header)
				f.SetCellStyle("Sheet1", "I1", "I1", style_header)
				f.SetCellStyle("Sheet1", "J1", "J1", style_header)
				f.SetCellStyle("Sheet1", "K1", "K1", style_header)
				f.SetCellStyle("Sheet1", "L1", "L1", style_header)
				f.SetCellStyle("Sheet1", "M1", "M1", style_header)
				f.SetCellStyle("Sheet1", "N1", "N1", style_header)
				//f.SetCellStyle("Sheet1", "M1", "M1", style)
				//行
				list := records.List()
				if len(list) > 0 {
					count := 0
					for k, v := range list {

						id := gconv.Int(v["id"])
						mode := gconv.Int(v["mode"])
						_model := gconv.String(v["model"])
						day := gconv.Int(v["day"])
						para_pig_num := gconv.Int(v["para_pig_num"])
						pig_num := gconv.Int(v["pig_num"])
						son_num := gconv.Int(v["son_num"])
						day_use_feed_auto := gconv.Float32(v["day_use_feed_auto"])
						day_use_feed_man := gconv.Float32(v["day_use_feed_man"])
						day_use_feed := day_use_feed_man + day_use_feed_auto
						avg_feed := gconv.Float32(v["avg_feed"])
						health := gconv.String(v["health"])
						low_standard := gconv.Float32(v["low_standard"])
						standard := gconv.Float32(v["standard"])
						high_standard := gconv.Float32(v["high_standard"])

						if pig_num == 0 {
							//status_his的猪只数量没有，需要刷新status_his
							low_standard, standard, high_standard = hub.GetStandard(_model, mode, day)

							pig_num = para_pig_num
							if pig_num > 0 {
								avg_feed = day_use_feed / float32(pig_num)
							}

							if low_standard <= avg_feed && avg_feed <= high_standard {
								//正常采食
								health = "good"
							} else {
								if low_standard > avg_feed {
									//低采食
									health = "low"
								} else if high_standard < avg_feed {
									//高采食
									health = "high"
								}
							}

							//update
							his, _ := dao.T_hzfgw_node_status_his.GetById(id)
							if his != nil {
								his["pig_num"] = pig_num
								his["avg_feed"] = avg_feed
								his["low_standard"] = low_standard
								his["high_standard"] = high_standard
								his["standard"] = standard
								his["health"] = health
								his["lasttime"] = common.NowString()
								his["source"] = 1 //记录更新
								dao.T_hzfgw_node_status_his.Save(his)
							}
						}

						count++
						//行数限制
						if count > 1048000 {
							break
						}
						f.SetCellValue("Sheet1", fmt.Sprintf("A%d", k+2), gconv.String(v["farmname"]))
						f.SetCellValue("Sheet1", fmt.Sprintf("B%d", k+2), gconv.String(v["housename"]))
						f.SetCellValue("Sheet1", fmt.Sprintf("C%d", k+2), gconv.String(v["hnum"]))
						mode_str := ""
						mode = gconv.Int(v["mode"])
						//device_type := gconv.String(v["device_type"])
						mode_str = DMXFGW.GetModeDesc(_model, mode)

						/*if mode > 0 {
							f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), mode_str+" "+gconv.String(v["day"])+"天")
						} else {
							f.SetCellStyle("Sheet1", fmt.Sprintf("D%d", k+2), fmt.Sprintf("D%d", k+2), style_yellow_font)
							f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), mode_str)
						}*/

						if mode > 0 {
							f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), mode_str)

						} else {
							f.SetCellStyle("Sheet1", fmt.Sprintf("D%d", k+2), fmt.Sprintf("D%d", k+2), style_yellow_font)
							f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), mode_str)

						}

						f.SetCellValue("Sheet1", fmt.Sprintf("F%d", k+2), gtime.NewFromStr(gconv.String(v["his_date"])).Format(common.DATE_FORMAT))

						if mode == DMXFGW.FEED_MODE_LACTATION {
							//哺乳
							f.SetCellValue("Sheet1", fmt.Sprintf("E%d", k+2), fmt.Sprintf("母猪:%s天 仔猪:%s天", gconv.String(v["day"]), gconv.String(v["day"])))
							f.SetCellValue("Sheet1", fmt.Sprintf("G%d", k+2), fmt.Sprintf("母猪:%d 仔猪:%d", pig_num, son_num))
						} else if mode == DMXFGW.EMODE_IDLE {
							//停用
							f.SetCellValue("Sheet1", fmt.Sprintf("E%d", k+2), "-")
							f.SetCellValue("Sheet1", fmt.Sprintf("G%d", k+2), "-")

						} else {
							f.SetCellValue("Sheet1", fmt.Sprintf("E%d", k+2), gconv.String(v["day"]))
							f.SetCellValue("Sheet1", fmt.Sprintf("G%d", k+2), pig_num)
						}

						f.SetCellValue("Sheet1", fmt.Sprintf("H%d", k+2), fmt.Sprintf("%.2f", day_use_feed))

						f.SetCellValue("Sheet1", fmt.Sprintf("I%d", k+2), fmt.Sprintf("%.2f", avg_feed))

						var feed_str string
						if mode > 0 {
							if health == "low" {
								f.SetCellStyle("Sheet1", fmt.Sprintf("J%d", k+2), fmt.Sprintf("J%d", k+2), style_yellow_font)
								feed_str = "↓采食量低"
							} else if health == "good" {
								f.SetCellStyle("Sheet1", fmt.Sprintf("J%d", k+2), fmt.Sprintf("J%d", k+2), style_green_font)
								feed_str = "采食量达标"
							} else if health == "high" {
								f.SetCellStyle("Sheet1", fmt.Sprintf("J%d", k+2), fmt.Sprintf("J%d", k+2), style_yellow_light_font)
								feed_str = "↑采食量高"
							}
							f.SetCellValue("Sheet1", fmt.Sprintf("J%d", k+2), feed_str)
							f.SetCellValue("Sheet1", fmt.Sprintf("K%d", k+2), fmt.Sprintf("%.3f", low_standard))
							f.SetCellValue("Sheet1", fmt.Sprintf("L%d", k+2), fmt.Sprintf("%.3f", low_standard)+" - "+fmt.Sprintf("%.3f", high_standard))
							f.SetCellValue("Sheet1", fmt.Sprintf("M%d", k+2), fmt.Sprintf("%.3f", high_standard))
						} else {
							f.SetCellValue("Sheet1", fmt.Sprintf("J%d", k+2), "-")
							f.SetCellValue("Sheet1", fmt.Sprintf("K%d", k+2), "-")
							f.SetCellValue("Sheet1", fmt.Sprintf("L%d", k+2), "-")
							f.SetCellValue("Sheet1", fmt.Sprintf("M%d", k+2), "-")
						}

						water := gconv.Float32(v["day_use_water_auto"]) + gconv.Float32(v["day_use_water_man"])
						f.SetCellValue("Sheet1", fmt.Sprintf("N%d", k+2), fmt.Sprintf("%.2f", water))

					}
				}

				// 设置工作簿的默认工作表
				f.SetActiveSheet(index)

				f.Write(r.Response.Writer)
			}

		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
			r.Response.WriteJson(res)
		}
		r.ExitAll()
	}
}

// ExportHourFeed 小时采食记录
func (a *feed_his) ExportHourFeed(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}
	params := r.GetQueryMap()
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	sn := gconv.String(params["sn"])
	where := " rectime>'2022-01-01' and rectime<='2050-01-01' "
	if begin == "" || end == "" {
		res["code"] = -2
		res["msg"] = "非法参数"
		r.Response.WriteJson(res)
	} else if sn == "" {
		res["code"] = -2
		res["msg"] = "非法参数"
		r.Response.WriteJson(res)
	} else {
		where += fmt.Sprintf(" and rectime>='%s' ", begin)
		where += fmt.Sprintf(" and rectime<='%s' ", end)
		where += " and sn='" + sn + "'"
		where += " and tb_record=0  "
		where += " and begin_end=0  "

		claims := jwt.ExtractClaims(r)
		userid := claims["userid"].(string)
		url := r.URL.Path
		if dao.CheckApiPermission(url, r.Method, userid) {
			//管理员可以看到全部，其他角色按照权限获取
			if dao.IsAdmin(userid) || dao.IsService(userid) {
			} else {
				//where += fmt.Sprintf(" and addr in (SELECT device_addr FROM t_user_device WHERE userid='%s')",userid)
			}
			//db := g.DB(g.Cfg().GetString("custom.db_name"))
			//model := db.Model("t_hzfgw_record")
			//dt, error := model.Where(where).All()
			orders := " rectime desc "
			list := tdengine.GetRecords(fmt.Sprintf("SELECT * FROM `t_hzfgw_record` where %s order by %s", where, orders))
			//获取猪只数量
			var pig_num int
			pig_num = 0
			nodes, _ := dao.T_hzfgw_node_para.GetList(fmt.Sprintf("sn='%s'", sn))
			if len(nodes) > 0 {
				node := nodes[0]
				pig_num = gconv.Int(node["pig_num"])
			}

			f := excelize.NewFile()
			defer func() {
				if err := f.Close(); err != nil {
					g.Log().Line(true).Error(err)
				}
			}()

			// 创建一个工作表
			index, err := f.NewSheet("Sheet1")
			if err != nil {
				g.Log().Line(true).Error(err)
			}

			//样式
			style_header, _ := f.NewStyle(&excelize.Style{
				Fill:      excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
				Font:      &excelize.Font{Color: "#ffffff", Bold: true},
				Alignment: &excelize.Alignment{Vertical: "center", Horizontal: "center"},
			})

			//列宽
			f.SetColWidth("Sheet1", "A", "J", 20)

			// 标题
			f.SetCellValue("Sheet1", "A1", "日期")
			f.SetCellValue("Sheet1", "B1", "时间")
			f.SetCellValue("Sheet1", "C1", "小时总下料量(kg)")
			f.SetCellValue("Sheet1", "D1", "小时总下水量(L)")
			f.SetCellValue("Sheet1", "E1", "小时头均下料量(kg)")

			f.SetCellStyle("Sheet1", "A1", "A1", style_header)
			f.SetCellStyle("Sheet1", "B1", "B1", style_header)
			f.SetCellStyle("Sheet1", "C1", "C1", style_header)
			f.SetCellStyle("Sheet1", "D1", "D1", style_header)
			f.SetCellStyle("Sheet1", "E1", "E1", style_header)

			today := gtime.NewFromStr(gtime.Now().Format(common.DATE_FORMAT))
			//var hour_arr []int
			//var hour_desc_arr []string
			//var feed_arr []float32
			//var water_arr []float32
			//var avg_feed_arr []float32
			for i := 0; i < 24; i++ {
				hour := i
				//hour_arr = append(hour_arr, hour)
				start := today.Add(time.Duration(hour) * time.Hour).Format("H:00")
				finish := today.Add(time.Duration(hour+1) * time.Hour).Format("H:00")
				hour_desc := fmt.Sprintf("%s-%s", start, finish)

				var sum_feed float32
				var sum_water float32
				var avg_feed float32

				sum_feed = 0
				sum_water = 0
				avg_feed = 0

				if len(list) > 0 {
					for _, his := range list {
						feed_type := gconv.Int(his.Feed_type)
						amount := gconv.Float32(his.Amount)
						date := gtime.NewFromTime(his.Rectime).Format(common.DATE_TIME_FORMAT)
						if gtime.NewFromStr(date).Hour() == hour {
							if feed_type > 0 {
								sum_feed += amount
							} else {
								sum_water += amount
							}
						}
					}
				}

				if pig_num > 0 {
					avg_feed = sum_feed / float32(pig_num)
				} else {
					avg_feed = 0
				}

				//填写数据
				f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i+2), begin)
				f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i+2), hour_desc)
				f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i+2), common.FloatToStringTrimEndZero(sum_feed, 2))
				f.SetCellValue("Sheet1", fmt.Sprintf("D%d", i+2), common.FloatToStringTrimEndZero(sum_water, 2))
				f.SetCellValue("Sheet1", fmt.Sprintf("E%d", i+2), common.FloatToStringTrimEndZero(avg_feed, 2))
			}

			// 设置工作簿的默认工作表
			f.SetActiveSheet(index)
			f.Write(r.Response.Writer)
		}
	}
	r.ExitAll()
}
